<template>
  <div ref="chartDom" style="width: 100%; height: 450px"></div>
</template>

<script lang="ts" setup>
import * as echarts from "echarts";

const chartDom: any = ref();

let chartInstance: any = null;
let chartTestColor: string = "#808080";

let option = {
  tooltip: {
    trigger: "axis",
  },
  title: {
    text: "平台在线人数统计",
    textStyle: {
      color: chartTestColor,
    },
  },
  legend: {
    data: ["玩家", "开发者（游戏开发商和独立游戏作者）"],
    textStyle: {
      color: chartTestColor,
    },
  },
  xAxis: {
    type: "category",
    data: [
      "6小时前",
      "5小时前",
      "4小时前",
      "3小时前",
      "2小时前",
      "1小时前",
      "当前",
    ],
    boundaryGap: false,
  },
  yAxis: {
    type: "value",
  },
  series: [
    {
      name: "玩家",
      data: [2540, 1890, 1560, 2180, 2889, 3740, 3500],
      type: "line",
      smooth: true,
      itemStyle: {
        color: "#409eff",
      },
    },
    {
      name: "开发者（游戏开发商和独立游戏作者）",
      data: [50, 200, 140, 180, 120, 100, 89],
      type: "line",
      smooth: true,
      itemStyle: {
        color: "#6e5bb3",
      },
    },
  ],
};

function initCharts() {
  if (!chartDom.value) return;

  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }

  chartInstance = echarts.init(chartDom.value);
  chartInstance.setOption(option);

  window.addEventListener("resize", function () {
    resizeChart();
  });
}

function resizeChart() {
  if (chartInstance) {
    chartInstance.resize();
  }
}

onMounted(() => {
  nextTick(() => {
    initCharts();
  });
});

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
  window.removeEventListener("resize", resizeChart);
});
</script>
